package com.sca.order.controller;

import com.sca.order.entity.Order;
import com.sca.order.service.OrderService;
import com.sca.product.entity.CommonResult;
import com.sca.product.entity.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
public class OrderController {
    private final static String PAYMENT_URL = "http://cloud-product-service";

    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private OrderService orderService;

    @GetMapping("/consumer/order/get/{id}")
    public CommonResult<Integer> getPaymentById(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL+"/product/get/"+id,CommonResult.class);
    }

    @GetMapping("/consumer/order/create")
    public CommonResult<Product> create(Product payment) {
        return restTemplate.postForObject(PAYMENT_URL+"/product/create",payment,CommonResult.class);
    }

    @PostMapping("/consumer/order/createorder")
    public CommonResult<Order> createOrder(@RequestBody Order payment) {
        try {
            int result = orderService.create(payment);
            log.info("****插入结果：" + result);
            if (result > 0) {
                return new CommonResult(200, "插入数据库成功", result);
            } else {
                return new CommonResult(444, "插入数据库失败", null);
            }
        } catch (Exception e) {
            log.info(e.toString());
            return new CommonResult(500, "插入数据库失败", null);
        }
    }
}
